#include<iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>

#define MESSAGE_LEN 1024
#define PORT 8112

using namespace std;

int main(){
	int socket_fd;
	int ret=-1;
	char sendbuf[MESSAGE_LEN]={0,};
        char recvbuf[MESSAGE_LEN]={0,};
	
	struct sockaddr_in Server_addr;
	int len=sizeof(Server_addr);
	Server_addr.sin_family= AF_INET;
        Server_addr.sin_port  = PORT;
        Server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	
	socket_fd=socket(AF_INET,SOCK_DGRAM,0);
	if(socket_fd<0){
                cout<<"failed to create socket!"<<endl;
                exit(-1);
        }
	while(1){
		memset(sendbuf,0,sizeof(sendbuf));
        	cout<<"client start to send data!"<<endl;
        	cout<<"please send data:"<<endl;
        	fgets(sendbuf,sizeof(sendbuf)-1,stdin);
        	ret=sendto(socket_fd,sendbuf,MESSAGE_LEN,0,(struct sockaddr *) &Server_addr, len);
        	if(ret<=0){
                        cout<<"failed to send data! disconnected"<<endl;
                        exit(-1);
                }

        	ret=recvfrom(socket_fd,recvbuf,MESSAGE_LEN,0,(struct sockaddr *) &Server_addr, (socklen_t*)&len);
        	recvbuf[ret]='\0';
        	cout<<"received data is:"<<recvbuf<<endl;
	}
	
	
	close(socket_fd);
	return 0;
}
